package com.soujiayi.activity;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import com.google.ads.AdRequest;
import com.google.ads.AdSize;
import com.google.ads.AdView;
import com.soujiayi.model.TuanMain;
import com.soujiayi.net.ImageLoader;
import com.soujiayi.store.DatabaseManager;
import com.soujiayi.util.Constants;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.StrikethroughSpan;
import android.text.style.UnderlineSpan;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

public class TuanDetailActivity extends Activity {

	private TextView tv_tuandetail_header;
	private TextView tv_tuandetail_price;
	private TextView tv_tuandetail_value;
	private TextView tv_tuandetail_rebate;
	private TextView tv_tuandetail_time;
	private TextView tv_tuandetail_save;
	private TextView tv_tuandetail_source;
	private ImageView imageView;
	private AdView adView;
	private boolean cancelThread = false;
	private int width;// 屏宽
	private int height;// 屏高
	private ImageLoader imageLoader;
	private String url;
	private String title;
	private long starttime;
	private long endtime;
	private String s_remain;
	private String s_finished;
	private String s_notstart;
	private String s_day;
	private String s_hour;
	private String s_minute;
	private String s_second;
	private long currenttime;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		// requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
		((MyApplication) this.getApplication()).addActivity(this);
		setContentView(R.layout.tuan_detail);
		imageLoader = new ImageLoader(this, true, 250, 176, 1);
		initView();
		loadData();
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		if (adView != null) {
			adView.destroy();
		}
		cancelThread = true;
		super.onDestroy();
	}

	public void initView() {
		tv_tuandetail_header = (TextView) this
				.findViewById(R.id.tv_tuandetail_header);
		tv_tuandetail_price = (TextView) this
				.findViewById(R.id.tv_tuandetail_price);
		tv_tuandetail_value = (TextView) this
				.findViewById(R.id.tv_tuandetail_value);
		tv_tuandetail_rebate = (TextView) this
				.findViewById(R.id.tv_tuandetail_rebate);
		tv_tuandetail_time = (TextView) this
				.findViewById(R.id.tv_tuandetail_time);
		tv_tuandetail_source = (TextView) this
				.findViewById(R.id.tv_tuandetail_source);
		tv_tuandetail_save = (TextView) this
				.findViewById(R.id.tv_tuandetail_save);
		imageView = (ImageView) this.findViewById(R.id.iv_tuandetail_pic);

		adView = (AdView) this.findViewById(R.id.av_tuandetail_ad);
		Map<String, Object> extras = new HashMap<String, Object>();
		extras.put("color_bg", "5f970e");
		extras.put("color_bg_top", "5f970e");
		extras.put("color_border", "FFFFFF");
		extras.put("color_link", "FFFFFF");
		extras.put("color_text", "FFFFFF");
		extras.put("color_url", "0066CC");

		AdRequest adRequest = new AdRequest();
		adRequest.setExtras(extras);
		adView.loadAd(adRequest);

	}

	// public void initData() {
	//
	// setProgressBarIndeterminateVisibility(true);
	// new Thread(new Runnable() {
	// @Override
	// public void run() {
	// // TODO Auto-generated method stub
	// try {
	// loadData();
	// setProgressBarIndeterminateVisibility(false);
	// } catch (Exception e) {
	// // TODO Auto-generated catch block
	// e.printStackTrace();
	// }
	// }
	// }).start();
	// }

	public void loadData() {
		TuanMain tuanMain = new TuanMain();
		tuanMain = (TuanMain) (this.getIntent()
				.getSerializableExtra(Constants.TUAN_MAIN));

		if (tuanMain != null) {
			title = tuanMain.getName();
			String price = tuanMain.getPrice();
			String value = tuanMain.getValue();
			String rebate = tuanMain.getRebate();
			String siteName = tuanMain.getSitename();
			String cityName = this.getIntent().getStringExtra(
					Constants.TUAN_CITY);
			// String siteurl = tuanMain.getSiteurl();
			// String buyurl = tuanMain.getBuyurl();
			url = tuanMain.getDetailurl();
			// String site_detail = tuanMain.getSite_detail();
			// String ismajor = tuanMain.getIsmajor();
			starttime = Long.valueOf(tuanMain.getStartime());
			endtime = Long.valueOf(tuanMain.getEndtime());
			currenttime = new Date().getTime() / 1000;
			s_remain = this.getString(R.string.tuan_tv_time);
			s_finished = this.getString(R.string.tuan_tv_finished);
			s_notstart = this.getString(R.string.tuan_tv_notstart);
			s_day = this.getString(R.string.tuan_tv_day);
			s_hour = this.getString(R.string.tuan_tv_hour);
			s_minute = this.getString(R.string.tuan_tv_minute);
			s_second = this.getString(R.string.tuan_tv_second);

			DisplayMetrics dm = new DisplayMetrics();
			dm = this.getResources().getDisplayMetrics();
			width = (int) (250 * dm.density);
			height = (int) (176 * dm.density);
			String cover = tuanMain.getCover().replace(".jpg",
					"." + width + "x" + height + ".jpg");

			if (price.indexOf(".") != -1) {
				int num = 0;
				num = price.indexOf(".");
				String dianAfter = price.substring(0, num + 1);
				String afterData = price.replace(dianAfter, "");
				if (afterData.length() < 2) {
					afterData = afterData + "0";
				}
				price = price.substring(0, num) + "."
						+ afterData.substring(0, 2);
			} else
				price = price + ".00";

			if (value.indexOf(".") != -1) {
				int num = 0;
				num = value.indexOf(".");
				String dianAfter = value.substring(0, num + 1);
				String afterData = value.replace(dianAfter, "");
				if (afterData.length() < 2) {
					afterData = afterData + "0";
				}
				value = value.substring(0, num) + "."
						+ afterData.substring(0, 2);
			} else
				value = value + ".00";

			float f = Float.valueOf(value) - Float.valueOf(price);
			DecimalFormat fnum = new DecimalFormat("##0.00");
			String save = fnum.format(f);
			;

			if (rebate.indexOf(".") != -1) {
				int num = 0;
				num = rebate.indexOf(".");
				String dianAfter = rebate.substring(0, num + 1);
				String afterData = rebate.replace(dianAfter, "");
				if (afterData.length() < 2) {
					afterData = afterData + "0";
				}
				rebate = rebate.substring(0, num) + "."
						+ afterData.substring(0, 2);
			} else
				rebate = rebate + ".00";

			tv_tuandetail_header.setText(cityName + "  " + siteName + ":  "
					+ title);
			tv_tuandetail_price.setText("￥" + price+this.getString(R.string.price_unit));
			SpannableString spanString = new SpannableString(this.getString(
					R.string.tuan_tv_sourcepri).replace("?", value));
			StrikethroughSpan span = new StrikethroughSpan();
			spanString.setSpan(span, 0, spanString.length(),
					Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
			tv_tuandetail_value.setText(spanString);
			tv_tuandetail_rebate.setText(this
					.getString(R.string.tuan_tv_rebate) + rebate);
			tv_tuandetail_save.setText(this.getString(R.string.tuan_tv_save)
					.replace("?", save));
			tv_tuandetail_source.setText(this
					.getString(R.string.tuan_tv_source) + siteName);
			imageLoader.DisplayImage(cover, imageView);
			if (currenttime <= endtime && currenttime >= starttime) {
				new Thread(new MyThread()).start();
			} else if (currenttime < starttime)
				tv_tuandetail_time.setText(s_remain + s_finished);
			else if (currenttime > endtime)
				tv_tuandetail_time.setText(s_remain + s_notstart);
		}

	}

	public void goToLook(View view) {
		Intent intent = new Intent(TuanDetailActivity.this,
				TuanDetailWebActivity.class);
		intent.putExtra(Constants.TUAN_DETAIL_URL, url);
		intent.putExtra(Constants.PRODUCT_NAME, title);
		startActivity(intent);
	}

	public void backToHome(View view) {
		Intent intent = new Intent(TuanDetailActivity.this, IndexActivity.class);
		startActivity(intent);
		this.finish();
		overridePendingTransition(R.anim.push_down_in, R.anim.push_down_out);
	}

	public void back(View view) {
		this.finish();
		overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
	}

	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		super.onBackPressed();
		this.finish();
		overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
	}

	Handler handler = new Handler() { // handle
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				try {
					{
						long day, hour, minute, second, distTime;
						int mi = 60;
						int hh = mi * 60;
						int dd = hh * 24;

						distTime = endtime - currenttime;
						day = distTime / dd;
						hour = (distTime - day * dd) / hh;
						minute = (distTime - day * dd - hour * hh) / mi;
						second = distTime - day * dd - hour * hh - minute * mi;

						String strDay = day < 10 ? "0" + day : "" + day;
						String strHour = hour < 10 ? "0" + hour : "" + hour;
						String strMinute = minute < 10 ? "0" + minute : ""
								+ minute;
						String strSecond = second < 10 ? "0" + second : ""
								+ second;
						if (distTime > 0) {
							tv_tuandetail_time.setText(s_remain + strDay
									+ s_day + strHour + s_hour + strMinute
									+ s_minute + strSecond + s_second);
							currenttime = currenttime + 1;
						} else
							tv_tuandetail_time.setText(s_remain + s_finished);
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			super.handleMessage(msg);
		}
	};

	public class MyThread implements Runnable { // thread
		@Override
		public void run() {
			while (!cancelThread) {
				try {
					Thread.sleep(1000); // sleep 1000ms
					Message message = new Message();
					message.what = 1;
					handler.sendMessage(message);
				} catch (Exception e) {
				}
			}
		}
	}
}
